package com.xumt.hwHMSdemo;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.huawei.hmf.tasks.OnFailureListener;
import com.huawei.hmf.tasks.OnSuccessListener;
import com.huawei.hmf.tasks.Task;
import com.huawei.hms.common.ApiException;
import com.huawei.hms.support.account.AccountAuthManager;
import com.huawei.hms.support.account.request.AccountAuthParams;
import com.huawei.hms.support.account.request.AccountAuthParamsHelper;
import com.huawei.hms.support.account.result.AuthAccount;
import com.huawei.hms.support.account.service.AccountAuthService;
import com.xumt.hwHMSdemo.cannectSb.HttpRequest;

public class Login2 extends AppCompatActivity {
    public static final String TAG = "HuaweiIdActivity";
    public static AccountAuthService mAuthManager;
    public static String usernamen;
    private AccountAuthParams mAuthParam;
    private  String result;
    private  String isvip=null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login2);
        Intent intent=new Intent(Login2.this,MainActivity.class);
        silence(intent);

        com.huawei.hms.support.hwid.ui.HuaweiIdAuthButton huaweibutton = (com.huawei.hms.support.hwid.ui.HuaweiIdAuthButton) findViewById(R.id.hwid_signin);
        huaweibutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signInCode();
            }
        });
        Button button1 = (Button) findViewById(R.id.Login);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login(intent);
            }
        });

        Button button2 = (Button) findViewById(R.id.register);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                register();
            }
        });

    }

    public void signInCode() {
        mAuthParam = new AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM)
                .setIdToken()
                .createParams();
        mAuthManager = AccountAuthManager.getService(Login2.this, mAuthParam);
        startActivityForResult(mAuthManager.getSignInIntent(), Constant.REQUEST_SIGN_IN_LOGIN);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String vip="true";
        if (requestCode == Constant.REQUEST_SIGN_IN_LOGIN) {
            //login success
            //get user message by parseAuthResultFromIntent
            Task<AuthAccount> authAccountTask = AccountAuthManager.parseAuthResultFromIntent(data);
            if (authAccountTask.isSuccessful()) {
                AuthAccount authAccount = authAccountTask.getResult();
                Log.i(TAG, authAccount.getDisplayName() + " signIn success ");
                Log.i(TAG, "AccessToken: " + authAccount.getIdToken());
                Log.i(TAG,"OpenId:"+authAccount.getOpenId());
                Toast.makeText(Login2.this, "Wellcome"+authAccount.getDisplayName(), Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(this, MainActivity.class);
                intent.putExtra(MainActivity.IS_VIP,vip);
                startActivity(intent);

            } else {
                Log.i(TAG, "signIn failed: " + ((ApiException) authAccountTask.getException()).getStatusCode());
            }
        }
//        if (requestCode == Constant.REQUEST_SIGN_IN_LOGIN_CODE) {
//            //login success
//            Task<AuthAccount> authAccountTask = AccountAuthManager.parseAuthResultFromIntent(data);
//            if (authAccountTask.isSuccessful()) {
//                AuthAccount authAccount = authAccountTask.getResult();
//                Log.i(TAG, "signIn get code success.");
//                Log.i(TAG, "ServerAuthCode: " + authAccount.getAuthorizationCode());
//                Toast.makeText(Login2.this, "Wellcome"+authAccount.getDisplayName(), Toast.LENGTH_SHORT).show();
//                Intent intent = new Intent(this, MainActivity.class);
//                startActivity(intent);
//                /**** english doc:For security reasons, the operation of changing the code to an AT must be performed on your server. The code is only an example and cannot be run. ****/
//                /**********************************************************************************************/
//            } else {
//                Toast.makeText(Login2.this, "Huwwei_LOGING_error", Toast.LENGTH_SHORT).show();
//                Log.i(TAG, "signIn get code failed: " + ((ApiException) authAccountTask.getException()).getStatusCode());
//            }
//        }
    }

    private void silence(Intent intent) {
//        mAuthParam = new AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM).createParams();
//        mAuthManager = AccountAuthManager.getService(Login2.this, mAuthParam);
        if(mAuthManager!=null)
        {
            Task<AuthAccount> task = mAuthManager.silentSignIn();
            task.addOnSuccessListener(new OnSuccessListener<AuthAccount>() {
                @Override
                public void onSuccess(AuthAccount authHuaweiId) {
                    Log.i(TAG, "dispalyName:" + authHuaweiId.getDisplayName());
                    Toast.makeText(Login2.this, "Silence success！", Toast.LENGTH_SHORT).show();
                    startActivity(intent);
                }

            });
            task.addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(Exception e) {
                    if (e instanceof ApiException) {
                        ApiException apiException = (ApiException) e;
                        Log.i(TAG, "Sign failed Status:" + apiException.getStatusCode());
                    }
                }
            });
        }

    }
private void login(Intent intent)  {
    EditText editText = findViewById(R.id.accout_text);
    EditText editText1 = findViewById(R.id.password_text);
    String thisusername = editText.getText().toString();
    String thispassword = editText1.getText().toString();
    usernamen=thisusername;
    if(thisusername.length()>0&&thispassword.length()>0) {
        new Thread() {
            public void run() {
                try {
                    HttpRequest request = new HttpRequest();
                    result = request.sendGet("http://169.254.132.31:8081/user/login", "username=" + thisusername + "&" + "password=" + thispassword);
                    isvip = request.sendGet("http://169.254.132.31:8081/user/isvip", "username=" + thisusername );
                    //   System.out.println(request.sendGet("http://169.254.67.221:8080/user/login", "username=wang&password=123"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("结果是" + result);
        if (result != null && result.length() > 2) {
            AlertDialog alertDialog1 = new AlertDialog.Builder(this)
                    .setTitle("登录成功")//标题
                    .setMessage("用户登录成功")//内容
                    .setIcon(R.mipmap.ic_launcher)//图标
                    .create();
            alertDialog1.show();
            intent.putExtra(MainActivity.IS_VIP,isvip);
            startActivity(intent);
            if(isvip.equals("true"))
            {
                System.out.println("vip");
                //进入vip主页
            }
            else
            {
                System.out.println("novip");
                //进入非vip主页
            }
        } else {
            AlertDialog alertDialog1 = new AlertDialog.Builder(this)
                    .setTitle("登录失败")//标题
                    .setMessage("账户或密码不正确")//内容
                    .setIcon(R.mipmap.ic_launcher)//图标
                    .create();
            alertDialog1.show();
        }
    }
    else
    {
        AlertDialog alertDialog1 = new AlertDialog.Builder(this)
                .setTitle("登录失败")//标题
                .setMessage("请填写账号和密码")//内容
                .setIcon(R.mipmap.ic_launcher)//图标
                .create();
        alertDialog1.show();
    }
}

    private void register()  {
        EditText editText = findViewById(R.id.accout_text);
        EditText editText1 = findViewById(R.id.password_text);
        String thisusername = editText.getText().toString();
        usernamen=thisusername;
        String thispassword = editText1.getText().toString();
//        HttpRequest request = new HttpRequest();
//        result= request.sendGet("http://169.254.67.221:8080/user/login","username="+thisusername +"&" +"password="+thispassword);
        if(thisusername.length()>0&&thispassword.length()>0) {
            new Thread() {
                public void run() {
                    try {
                        HttpRequest request = new HttpRequest();
                        result = request.sendGet("http://169.254.132.31:8081/user/register", "username=" + thisusername + "&" + "password=" + thispassword);
                        //   System.out.println(request.sendGet("http://169.254.67.221:8080/user/login", "username=wang&password=123"));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }.start();
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("结果是" + result);
            if (result.equals("true")) {
                AlertDialog alertDialog1 = new AlertDialog.Builder(this)
                        .setTitle("注册成功")//标题
                        .setMessage("用户注册成功")//内容
                        .setIcon(R.mipmap.ic_launcher)//图标
                        .create();
                alertDialog1.show();

            } else {
                AlertDialog alertDialog1 = new AlertDialog.Builder(this)
                        .setTitle("注册失败")//标题
                        .setMessage("用户名已存在")//内容
                        .setIcon(R.mipmap.ic_launcher)//图标
                        .create();
                alertDialog1.show();
            }
        }
        else
        {
            AlertDialog alertDialog1 = new AlertDialog.Builder(this)
                    .setTitle("注册失败")//标题
                    .setMessage("请填写账号和密码")//内容
                    .setIcon(R.mipmap.ic_launcher)//图标
                    .create();
            alertDialog1.show();
        }
    }
}